import {
  apiGetBusinessClassificationSave,
  apiGetBusinessClassificationUpdate,
} from '@/services/type';
import {
  ModalForm,
  ModalFormProps,
  ProForm,
  ProFormText,
} from '@ant-design/pro-components';
import { message, Upload, UploadFile, UploadProps } from 'antd';
import {useEffect, useState} from 'react';
import React from 'react/index';

export const EditModal: React.FC<{
  record?: any;
  onFinish?: Function;
  children: ModalFormProps['trigger'];
}> = ({ children, record, onFinish }) => {
  const [open, setOpen] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  useEffect(()=>{
    setFileList(record?.resourceVOList)
  },[record])

  return (
    <ModalForm
      title={'修改'}
      trigger={children}
      initialValues={record}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      onOpenChange={setOpen}
      layout="vertical"
      grid={true}
      onFinish={async (values) => {
        if (fileList && fileList?.length > 0) {
          fileList?.map(o=>{
            if(o.response){
              o.url = o.response.data
            }
          })
          values.resourceVOList = fileList;
          console.log('fileList', fileList);
        }else{
          values.resourceVOList = [];
        }
        const res = await (record
          ? apiGetBusinessClassificationUpdate
          : apiGetBusinessClassificationSave)(values);
        if (res.code === 200) {
          message.success(record ? '修改成功' : '新增成功');
          onFinish?.();
          return true;
        } else {
          message.error(res.message);
        }

        return false;
      }}
    >
      <ProForm.Item hidden name="navId" />
      <ProFormText name="title" label="名称" />
      <ProFormText name="sortOrder" label="排序" />
      <div>图片</div>
      <Upload
        accept="image/png, image/jpeg"
        action="/obe/service/nav/upload"
        listType="picture-card"
        fileList={fileList}
        onChange={handleChange}
      >
        {fileList?.length >= 5 ? null : '上传'}
      </Upload>
    </ModalForm>
  );
};
